package spring.boot.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

@Component
public class NettyServer {
    private final Logger logger = LoggerFactory.getLogger(NettyServer.class);

    private final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    private final EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);

    private Channel channel = null;
    private ChannelFuture channelFuture = null;

    /**
     * 启动服务
     */
    public ChannelFuture run (InetSocketAddress address) {
        try {
            ServerBootstrap server = new ServerBootstrap();
            server.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new NettyServerChannelInitializer());


            channelFuture = server.bind(address).syncUninterruptibly();
            channel = channelFuture.channel();
        } catch (Exception e) {
            logger.error("Netty 启动 错误:", e);
        } finally {
            if (channelFuture != null && channelFuture.isSuccess()) {
                logger.info("Netty服务启动成功，正在监听域名[" + address.getHostName() + "]下的[" + address.getPort() + "]端口， 开始接收连接。。。");
            } else {
                logger.error("Netty 服务 启动 失败!");
            }
        }
        return channelFuture;
    }

    public void destroy() {
        logger.info("开始停止 Netty 服务...");
        if(channel != null) {
            channel.close();
        }
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        logger.info("停止Netty服务成功!");
    }
}
